'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  const { deviceInfo } = event;

  // 参数校验
  if (!deviceInfo || !deviceInfo.de_name || !deviceInfo.de_model || !deviceInfo.de_location) {
    return {
      code: -1,
      message: '设备信息不完整'
    };
  }

  try {
    // 检查设备名称是否已存在
    const existDevice = await db.collection('devices')
      .where({
        de_name: deviceInfo.de_name
      })
      .get();

    if (existDevice.data && existDevice.data.length > 0) {
      return {
        code: -1,
        message: '设备名称已存在'
      };
    }

    // 添加设备
    const deviceData = {
      ...deviceInfo,
      create_time: Date.now(),
      update_time: Date.now()
    };

    const result = await db.collection('devices').add(deviceData);

    if (result.id) {
      return {
        code: 0,
        message: '添加成功',
        data: {
          deviceId: result.id
        }
      };
    } else {
      return {
        code: -1,
        message: '添加失败'
      };
    }
  } catch (error) {
    console.error('添加设备失败:', error);
    return {
      code: -1,
      message: '添加设备失败',
      error: error.message
    };
  }
}; 